//
//  AutoCloseLockView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/24.
//

import SwiftUI
import TLCLock

struct AutoCloseLockView: View {


    let device: LockDevice
    @State var duration: String = ""

    var body: some View {
        
        VStack {
            YxrInputView("时长(秒)", placeholderText: "0~255", text: $duration)
                .padding(.vertical, 10)
            
            YxrConfirmView(title: "确认", action: onTapConfirm).padding(.top, 50)
            
            LogView()
        }
        
        .yxrNavigationTitle("自动闭锁")
    }

    func onTapConfirm() {
        if duration.isEmpty {
            showToast("请输入自动闭锁时长")
            return
        }

        let time = duration.trimmingCharacters(in: .whitespaces)
        guard let second = Int(time) else {
            showToast("请输入正确的数字")
            return
        }

        if second > 255 || second < 0 {
            showToast("时长范围0~255")
            return
        }

        guard let lockKey = Server.getSecret(device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        lockTask(desc: "自动闭锁") {
            await device.autoCloseLock(second: UInt8(second), lockKey: lockKey, trackId: Server.testTrackId)
        }
    }
}
